package com.supermap.supermap.controller;

import com.alibaba.fastjson.JSONObject;
import com.supermap.analyst.spatialanalyst.OverlayAnalyst;
import com.supermap.analyst.spatialanalyst.OverlayAnalystParameter;
import com.supermap.data.*;
import com.supermap.data.conversion.*;
import com.supermap.supermap.utils.Result;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author chenGJ
 */
@RestController
@RequestMapping("/gis")
public class GisController {

    private Workspace workspace = new Workspace();
    /**
     * @MethodName: connection
     * @Description: 矢量数据的裁剪分析，使用region1和region2求交，结果数据字段保留region1中的name和region2中的code
     * @Param String
     * @Return: java.lang.String
     * @Author: chenGj
     * @Date: 2020/3/31 16:37
    **/
    @RequestMapping("/connection")
    public Object connection(){
        //建立工作空间
        Workspace workspace = new Workspace();
        //设置数据源
        DatasourceConnectionInfo datasourceConnection = new DatasourceConnectionInfo();
        datasourceConnection.setEngineType(EngineType.ORACLEPLUS);
        datasourceConnection.setServer("192.168.0.204:51521/qqhebdc");
        datasourceConnection.setUser("GISTEST");
        datasourceConnection.setPassword("salis");
        datasourceConnection.setAlias("gis");
        //工作空间打开数据源
        Datasource datasource = workspace.getDatasources().open(datasourceConnection);
        //被相交的数据集
        DatasetVector datasetIntersected = (DatasetVector) datasource.getDatasets().get("Region1");
        //相交的数据集
        DatasetVector datasetIntersect = (DatasetVector) datasource.getDatasets().get("Region2");
        if(null!=datasource.getDatasets().get("resultDatasetIntersect")){
            datasource.getDatasets().delete("resultDatasetIntersect");
        }
        //创建一个面矢量数据集，用于存储相交分析返回的结果
        String resultDatasetIntersectName  = datasource.getDatasets().getAvailableDatasetName("resultDatasetIntersect");
        DatasetVectorInfo datasetvectorInfoIntersect = new DatasetVectorInfo();
        datasetvectorInfoIntersect.setType(DatasetType.REGION);
        datasetvectorInfoIntersect.setName(resultDatasetIntersectName);
        datasetvectorInfoIntersect.setEncodeType(EncodeType.NONE);
        DatasetVector resultDatasetIntersect = datasource.getDatasets().create(datasetvectorInfoIntersect);
        if(null != resultDatasetIntersect){
            return getIntersect(workspace, datasourceConnection, datasetIntersected, datasetIntersect, resultDatasetIntersect);
        }else{
            return "结果集创建失败";
        }
    }

    /**
     * @MethodName: updateCode
     * @Description: 更新Region1矢量数据集NAME字段含有 医院 属性的图形，将其的code值更新为120
     * @Param String
     * @Return: java.lang.String
     * @Author: chenGj
     * @Date: 2020/3/31 16:36
    **/
    @RequestMapping("/updateCode/{code}")
    public String updateCode(@PathVariable("code")String code){
        //建立工作空间
        Workspace workspace = new Workspace();
        //设置数据源
        DatasourceConnectionInfo datasourceconnection = new DatasourceConnectionInfo();
        datasourceconnection.setEngineType(EngineType.ORACLEPLUS);
        datasourceconnection.setServer("192.168.0.204:51521/qqhebdc");
        datasourceconnection.setUser("GISTEST");
        datasourceconnection.setPassword("salis");
        datasourceconnection.setAlias("gis");
        //工作空间打开数据源
        Datasource datasource = workspace.getDatasources().open(datasourceconnection);
        //被相交的数据集
        DatasetVector datasetIntersected = (DatasetVector) datasource.getDatasets().get("Region1");
        //设置查询参数（动态数据，模糊查询）
        QueryParameter queryParameter = new QueryParameter();
        queryParameter.setCursorType(CursorType.DYNAMIC);
        queryParameter.setAttributeFilter("NAME like '%医院%'");
        Recordset recordset = datasetIntersected.query(queryParameter);
        recordset.moveFirst();
        //批量更新对象
        //Recordset.BatchEditor editor = recordset.getBatch();
        //Map map  = new HashMap();
        //map.put("CODE",code);
        //批量更新操作开始
        //editor.begin();
        while (!recordset.isEOF()){
            String name = recordset.getString("NAME");
            System.out.println("name-------------->"+name);
            String SMID = recordset.getString("SMID");
            System.out.println("SmUserID-------------->"+SMID);
            String CODE = recordset.getString("CODE");
            System.out.println("CODE-------------->"+CODE);
            //recordset.setValues(map);
            recordset.edit();
            recordset.setString("CODE",code);
            recordset.update();
            recordset.moveNext();
        }
        //批量更新
        //editor.update();
        recordset.dispose();
        datasourceconnection.dispose();
        workspace.dispose();
        return "CODE更新成功";
    }

    /**
     * @MethodName: createMemoryDateSource
     * @Description: 创建内存数据源，相交分析后把结果集给放在内存数据源中
     * @Param
     * @Return: java.lang.String
     * @Author: chenGj
     * @Date: 2020/4/2 16:08
    **/
    @RequestMapping("/createMemoryDateSource")
    public Object createMemoryDateSource(){
        Workspace workspace = new Workspace();
        //设置数据源
        DatasourceConnectionInfo datasourceConnection = new DatasourceConnectionInfo();
        datasourceConnection.setEngineType(EngineType.ORACLEPLUS);
        datasourceConnection.setServer("192.168.0.204:51521/qqhebdc");
        datasourceConnection.setUser("GISTEST");
        datasourceConnection.setPassword("salis");
        datasourceConnection.setAlias("gis");
        //工作空间打开数据源
        Datasource datasource = workspace.getDatasources().open(datasourceConnection);
        //被相交的数据集
        DatasetVector datasetIntersected = (DatasetVector) datasource.getDatasets().get("Region1");
        //相交的数据集
        DatasetVector datasetIntersect = (DatasetVector) datasource.getDatasets().get("Region2");

        // 设置数据源位置为内存中，类型为MEMORY
        DatasourceConnectionInfo info = new DatasourceConnectionInfo();
        info.setServer(":memory:");
        info.setEngineType(EngineType.MEMORY);
        Datasource datasourceMemory = workspace.getDatasources().create(info);

        //创建一个面矢量数据集，用于存储相交分析返回的结果
        String resultDatasetIntersectName  = datasourceMemory.getDatasets().getAvailableDatasetName("DatasourceMemory");
        DatasetVectorInfo datasetvectorInfoIntersect = new DatasetVectorInfo();
        datasetvectorInfoIntersect.setType(DatasetType.REGION);
        datasetvectorInfoIntersect.setName(resultDatasetIntersectName);
        datasetvectorInfoIntersect.setEncodeType(EncodeType.NONE);
        DatasetVector resultDatasetIntersect = datasourceMemory.getDatasets().create(datasetvectorInfoIntersect);
        if(datasourceMemory!=null){
            return getIntersect(workspace,datasourceConnection,datasetIntersected,datasetIntersect,resultDatasetIntersect);
        }
        return "创建内存数据源失败";
    }

    /**
     * 相交分析公共方法
     * @param workspace
     * @param datasourceConnection
     * @param datasetIntersected
     * @param datasetIntersect
     * @param resultDatasetIntersect
     * @return
     */
    private Object getIntersect(Workspace workspace, DatasourceConnectionInfo datasourceConnection, DatasetVector datasetIntersected, DatasetVector datasetIntersect, DatasetVector resultDatasetIntersect) {
        boolean isConvert = CoordSysTranslator.convert(resultDatasetIntersect,datasetIntersected.getPrjCoordSys(),new CoordSysTransParameter(),CoordSysTransMethod.China_3D_7P);
        if(isConvert){
            // 设置叠加分析参数(保留region1中的name和region2中的code)
            OverlayAnalystParameter overlayAnalystParamIntersect = new OverlayAnalystParameter();
            overlayAnalystParamIntersect.setSourceRetainedFields(new String[]{"NAME"});
            overlayAnalystParamIntersect.setOperationRetainedFields(new String[]{"NEWFIELD"});
            // 调用相交叠加分析方法实相交分析
            boolean isIntersect = OverlayAnalyst.intersect(datasetIntersected, datasetIntersect, resultDatasetIntersect, overlayAnalystParamIntersect);
            if(!isIntersect){
                return "相交分析失败";
            }else{
                //返回前台的json数据
                Object obj = Result.getPrjCoordSysAttributeGeoRegion(resultDatasetIntersect);
                datasourceConnection.dispose();
                workspace.dispose();
                return obj;
            }
        }else{
            return "坐标系统转换失败";
        }
    }

    /**
     * @MethodName: importDataSet
     * @Description: 导入数据集
     * @Param
     * @Return: java.lang.String
     * @Author: chenGj
     * @Date: 2020/4/3 13:16
    **/
    @RequestMapping("/importDataSet")
    public String importDataSet(){
        Workspace workspace = new Workspace();
        //设置数据源
        DatasourceConnectionInfo datasourceConnection = new DatasourceConnectionInfo();
        datasourceConnection.setEngineType(EngineType.ORACLEPLUS);
        datasourceConnection.setServer("192.168.0.204:51521/qqhebdc");
        datasourceConnection.setUser("GISTEST");
        datasourceConnection.setPassword("salis");
        datasourceConnection.setAlias("gis");
        //工作空间打开数据源
        Datasource datasource = workspace.getDatasources().open(datasourceConnection);
        if(null!=datasource){
            //导入shp文件（ImportSettingSHP 继承 ImportSetting）
            ImportSettingSHP importSettingSHP = new ImportSettingSHP();
            //设置需要导入的数据路径信息
            importSettingSHP.setSourceFilePath("C:\\Users\\Administrator\\Desktop\\test.shp");
            //设置导入文件的原始字符集类型
            importSettingSHP.setSourceFileCharset(Charset.ANSI);
            //设置当同名数据集存在时导入的模式
            importSettingSHP.setImportMode(ImportMode.OVERWRITE);
            //设置目标数据集的文件名称
            importSettingSHP.setTargetDatasetName("test");
            //设置需要导入的数据源对象
            importSettingSHP.setTargetDatasource(datasource);
            //导入数据类
            DataImport dataImport = new DataImport();
            dataImport.getImportSettings().add(importSettingSHP);
            ImportResult result = dataImport.run();
            if(result.getFailedSettings().length==0){
                return "导入成功";
            }else{
                return "导入失败";
            }
        }
        return "数据源打开失败";
    }

    /**
     * @MethodName: exportDataSet
     * @Description: 导出数据集
     * @Param
     * @Return: java.lang.String
     * @Author: chenGj
     * @Date: 2020/4/3 13:17
    **/
    @RequestMapping("/exportDataSet")
    public String exportDataSet(){
        Workspace workspace = new Workspace();
        //设置数据源
        DatasourceConnectionInfo datasourceConnection = new DatasourceConnectionInfo();
        datasourceConnection.setEngineType(EngineType.ORACLEPLUS);
        datasourceConnection.setServer("192.168.0.204:51521/qqhebdc");
        datasourceConnection.setUser("GISTEST");
        datasourceConnection.setPassword("salis");
        datasourceConnection.setAlias("gis");
        //工作空间打开数据源
        Datasource datasource = workspace.getDatasources().open(datasourceConnection);
        DatasetVector datasetVector = (DatasetVector) datasource.getDatasets().get("resultDatasetIntersect");
        datasetVector.open();
        if(datasetVector!=null){
            ExportSetting exportSetting = new ExportSetting();
            exportSetting.setSourceData(datasetVector);
            exportSetting.setTargetFileType(FileType.SHP);
            exportSetting.setTargetFileCharset(Charset.ANSI);
            exportSetting.setIgnoreFieldNames(new String[]{"SmUserID"});
//            ExportFieldModifyInfo fieldModifyInfo = new ExportFieldModifyInfo();
//            fieldModifyInfo.setName("NAME");
//            fieldModifyInfo.setType(FieldType.TEXT);
//            fieldModifyInfo.setScale(255);
            ExportFieldModifyInfo [] exportFieldModifyInfos = new ExportFieldModifyInfo[]{new ExportFieldModifyInfo()};
            exportFieldModifyInfos[0].setName("CODE");
            exportFieldModifyInfos[0].setType(FieldType.TEXT);
            exportSetting.setModifyFieldInfos(exportFieldModifyInfos);
            exportSetting.setTargetFilePath("C:\\Users\\Administrator\\Desktop\\test.shp");
            exportSetting.setOverwrite(true);

            DataExport dataExport = new DataExport();
            dataExport.getExportSettings().add(exportSetting);
            ExportResult result = dataExport.run();
            if(result.getFailedSettings().length==0){
                return "导出成功";
            }else{
                return "导出失败";
            }
        }else{
            return "打开数据集失败";
        }
    }
}
